import { useState, useEffect } from 'react'
import axios from 'axios'
import PhotoUploader from './components/PhotoUploader'
import PhotoGallery from './components/PhotoGallery'
import './App.css'

function App() {
  const [photos, setPhotos] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  // 获取所有照片
  const fetchPhotos = async () => {
    try {
      setLoading(true)
      setError('')
      const response = await axios.get('/api/photos')
      setPhotos(response.data)
    } catch (err) {
      console.error('获取照片失败:', err)
      setError('获取照片失败，请刷新页面重试')
    } finally {
      setLoading(false)
    }
  }

  // 组件挂载时获取照片
  useEffect(() => {
    fetchPhotos()
  }, [])

  // 上传照片后刷新照片列表
  const handlePhotoUploaded = (newPhoto) => {
    // 为新上传的照片添加url字段
    const photoWithUrl = {
      ...newPhoto,
      url: `http://localhost:${window.location.port || 9999}${newPhoto.path}`
    }
    // 将新上传的照片添加到列表
    setPhotos(prevPhotos => [photoWithUrl, ...prevPhotos])
  }

  return (
    <div className="container">
      <header className="app-header">
        <h1 className="app-title">照片墙</h1>
        <p className="app-description">上传并分享您的精彩照片</p>
      </header>

      <PhotoUploader onPhotoUploaded={handlePhotoUploaded} />
      
      {error && <div className="error-message">{error}</div>}
      
      {loading ? (
        <div className="loading">加载中...</div>
      ) : (
        <PhotoGallery photos={photos} />
      )}
    </div>
  )
}

export default App